package com.premedsidekick;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DefaultEntryDatabaseAdapter {
	int DATABASE_VERSION = 1;
	String DATABASE_NAME;
	String KEY_ROWID = "_id";
	String KEY_NAME = "name";
	DefaultEntryDatabaseHelper dbHelper;
	SQLiteDatabase database;
	Context context;
	ContentValues values;
	
	public DefaultEntryDatabaseAdapter(Context context, String name) {
		this.context = context;
		DATABASE_NAME = name;
	}
	public DefaultEntryDatabaseAdapter open() throws SQLException {
		dbHelper = new DefaultEntryDatabaseHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
		
	}
	public void close() {
		dbHelper.close();
	}
	
	public long create(String name) {
		values = new ContentValues();
		values.put(KEY_NAME, name);
		return database.insert(DATABASE_NAME, null, values);
	}
	public boolean update(long rowId, String name) {
		values = new ContentValues();
		values.put(KEY_NAME, name);
		return database.update(DATABASE_NAME, values, KEY_ROWID + "=" + rowId, null) > 0;
	}
	public boolean delete(long rowId) {
		return database.delete(DATABASE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
	}
	public Cursor getAll() {
		Cursor cursor = database.query(DATABASE_NAME, new String[] {KEY_ROWID, KEY_NAME}, 
			null, null, null, null, null);
		if (cursor.getCount() == 0 || cursor == null) {
			create("Insert name");
			cursor = database.query(DATABASE_NAME, new String[] {KEY_ROWID, KEY_NAME}, 
				null, null, null, null, null);
		}
		return cursor;
	}
	
	public class DefaultEntryDatabaseHelper extends SQLiteOpenHelper {
		DefaultEntryDatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + DATABASE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
				KEY_NAME + " TEXT);");
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}
	}
}
